package com.fr.mongodb;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

/**
*作者：furong
*日期：2016年11月19日
*时间：下午5:30:58
*/
public class MongodbTest {
    private static MongoClient client = null;
    static {
        MongoCredential credential = MongoCredential.createCredential("root", "admin", "123456".toCharArray());
        client = new MongoClient(new ServerAddress("192.168.50.50", 27017), Arrays.asList(credential));
    }

    public static void main(String[] args) {
        System.out.println(client.getDatabaseNames());
        MongoDatabase data = client.getDatabase("test");
        // insert(data);
        find(data);

    }

    private static Map<String, Object> createMap(int i) {
        Map<String, Object> map = new HashMap<>();
        map.put("a", i);
        map.put("b", i * i);
        map.put("c", Math.sqrt(i));
        return map;
    }

    private static void insert(MongoDatabase data) {
        MongoCollection<Document> coll = data.getCollection("aaa");
        List<Document> documents = new ArrayList<>();
        for (int i = 1; i < 1000; i++) {
            documents.add(new Document(createMap(i)));
        }
        coll.insertMany(documents);
    }

    private static void find(MongoDatabase data) {
        MongoCollection<Document> coll = data.getCollection("aaa");
        FindIterable<Document> rs = coll.find();
        Document doc = null;
        MongoCursor<Document> mc = rs.iterator();
        while ((doc = rs.first()) != null) {
            System.out.println(doc);
        }
    }
}
